import {defineStore} from 'pinia';
import {v4 as uuid} from 'uuid';
import eventBus, {Events} from '@/event-bus';
import type {Block, BlockType, Point} from '@/types';
import config from '@/config';

export const useBlocksStore = defineStore('blocks', {
    state: () => ({
        // 所有块的集合
        blocks: [] as Block[],
        // 当前选中的块ID
        selectedBlockId: null as string | null,
        // 块的计数器，用于生成默认名称
        blockCounters: {
            car: 0,
            flatcar: 0,
            pedestrian: 0,
            bicycle: 0
        }
    }),

    getters: {
        /**
         * 获取当前选中的块
         */
        selectedBlock(state) {
            return state.selectedBlockId
                ? state.blocks.find(block => block.id === state.selectedBlockId)
                : null;
        },

        /**
         * 按类型获取块列表
         */
        blocksByType: (state) => (type: BlockType) => {
            return state.blocks.filter(block => block.type === type);
        }
    },

    actions: {
        /**
         * 添加新块
         * @param type 块类型
         * @param position 位置（实际坐标）
         * @returns 新创建的块
         */
        addBlock(type: BlockType, position: Point): Block {
            // 增加对应类型的计数器
            this.blockCounters[type]++;

            // 创建新块
            const defaults = config.blockDefaults[type];
            const img = this.buildImage(type)
            const newBlock: Block = {
                id: uuid(),
                name: `${type.charAt(0).toUpperCase() + type.slice(1)} ${this.blockCounters[type]}`,
                type,
                x: position.x,
                y: position.y,
                heading: 0, // 默认朝向
                color: defaults.color,
                collision: {...defaults.collision},
                source: {
                    img: img
                },
                speed: defaults.speed,
                acceleration: defaults.acceleration
            };

            // 添加到列表
            this.blocks.push(newBlock);

            // 选中新添加的块
            this.selectBlock(newBlock.id);

            // 发出块添加事件
            eventBus.emit(Events.BLOCK_ADDED, newBlock);

            return newBlock;
        },

        /**
         * 删除块
         * @param id 块ID
         */
        deleteBlock(id: string): void {
            const index = this.blocks.findIndex(block => block.id === id);
            if (index !== -1) {
                // 移除块
                this.blocks.splice(index, 1);

                // 如果删除的是选中的块，清除选中状态
                if (this.selectedBlockId === id) {
                    this.selectedBlockId = null;
                }

                // 发出块删除事件
                eventBus.emit(Events.BLOCK_DELETED, id);
            }
        },

        /**
         * 更新块属性
         * @param id 块ID
         * @param updates 要更新的属性
         */
        updateBlock(id: string, updates: Partial<Block>): void {
            const index = this.blocks.findIndex(block => block.id === id);
            if (index !== -1) {
                // 合并更新
                this.blocks[index] = {...this.blocks[index], ...updates};

                // 发出块更新事件
                eventBus.emit(Events.BLOCK_UPDATED, this.blocks[index]);
            }
        },

        // /**
        //  * 移动块
        //  * @param id 块ID
        //  * @param delta 位移量（实际坐标）
        //  */
        // moveBlock(id: string, delta: Point): void {
        //     this.updateBlock(id, {
        //         x: parseFloat((this.blocks.find((b) => b.id === id)?.x + delta.x || 0).toFixed(3)),
        //         y: parseFloat((this.blocks.find((b) => b.id === id)?.y + delta.y || 0).toFixed(3))
        //     });
        // },

        /**
         * 旋转块
         * @param id 块ID
         * @param angle 旋转角度（度）
         */
        rotateBlock(id: string, angle: number): void {
            const block = this.blocks.find(b => b.id === id);
            if (block) {
                // 确保角度在0-360之间
                let newHeading = (block.heading + angle) % 360;
                if (newHeading < 0) newHeading += 360;

                this.updateBlock(id, {heading: newHeading});
            }
        },

        /**
         * 选择块
         * @param id 块ID
         */
        selectBlock(id: string | null): void {
            this.selectedBlockId = id;

            if (id) {
                const block = this.blocks.find(b => b.id === id);
                if (block) {
                    eventBus.emit(Events.BLOCK_SELECTED, block);
                }
            } else {
                eventBus.emit(Events.BLOCK_SELECTED, null);
            }
        },

        /**
         * 清除所有块
         */
        clearAllBlocks(): void {
            this.blocks = [];
            this.selectedBlockId = null;
            eventBus.emit(Events.SCENE_CLEARED);
        },

        /**
         * 批量设置块
         * @param blocks 块列表
         */
        setBlocks(blocks: Block[]): void {
            this.blocks = [...blocks];
            // 重置计数器
            this.resetCounters();
            eventBus.emit(Events.CANVAS_REFRESH);
        },

        /**
         * 重置计数器
         */
        resetCounters(): void {
            // 重置所有计数器为0
            Object.keys(this.blockCounters).forEach(key => {
                (this.blockCounters as any)[key] = 0;
            });

            // 根据现有块重新计算计数器
            this.blocks.forEach(block => {
                if (this.blockCounters[block.type] !== undefined) {
                    this.blockCounters[block.type]++;
                }
            });
        },
        buildImage(type: BlockType) {
            let src;
            switch (type) {
                case "car":
                    src = 'src/assets/icons/car.png'
                    break;
                case "flatcar":
                    src = 'src/assets/icons/flatcar.png'
                    break;
                default:
                    src = 'src/assets/icons/car.png'
            }
            const img = new Image()
            img.src = src
            return img
        }
    }
});
